<?PHP
error_reporting(E_ALL);
$relPath="../../pinc/";
require_once $relPath."dpinit.php";
include_once($relPath.'dp_main.inc');
include_once($relPath."DpTable.class.php");

$vsort      = Arg("vsort", "title");
$chkavail   = Arg("chkavail");
$chkinprog  = Arg("chkinprog");
$isdesc     = ArgBoolean("vdesc");

$User->IsLoggedIn()
    or RedirectToLogin();

if(! $User->IsLoggedIn())
{
    redirect_to_home();
    exit;
}

$username   = Arg("username");




if($username)
{
    if(    ! $User->IsSiteManager() 
        && ! $User->IsProjectFacilitator()
        && $username != $User->Username())
    {
        $username = $User->Username();
    }
}
else
{
$username = $User->Username();
}

$is_rnd_chk = array();
foreach(RoundIdsInOrder() as $roundid) {
    $is_rnd_chk[$roundid] = (! $vsort || IsArg($roundid));
}

// ---------------

$nameCaption =
        "<<a href='#' onclick='titlesort()'>"._("Title")."</a>";
$activeCaption = ">"._("My pages in <br /> progress") ;
$roundCaption = 
    "^<a href='#' onclick='statesort()'>"._("Current round")."</a>";
$daysCaption = "><a onclick='dayssort()'>"
                ._("Last Work<br />(Days Ago)")."</a>";
$diffsCaption = "><a onclick='diffsort()'>"
                ._("Newest diffs<br />(days ago)")."</a>";
$countCaption = "><a onclick='roundsort()'>"._("Round")
                ."<br />("._("pages saved").")</a>";

$tbl = new DpTable();

$tbl->AddColumn( $nameCaption,     null,    "_nameofwork" ) ;
$tbl->AddColumn( $activeCaption,   null,    "_pages_active" ) ;
$tbl->AddColumn( $daysCaption,     null,    "_event_time" ) ;
$tbl->AddColumn( $roundCaption,    null,    "_round_code" ) ;
$tbl->AddColumn( $countCaption,    null,    "_round_count" ) ;
$tbl->AddColumn( $diffsCaption,    null,    "_date_diffable" ) ;


switch( $vsort ) {
    case "title" :
        $orderby = $isdesc
                ? "ORDER BY nameofwork DESC, prs.sequence"
                : "ORDER BY nameofwork, prs.sequence" ;
        break ;

    case "days" :
        $orderby = $isdesc == true
                ? "ORDER BY max_round_event_time, prs.sequence"
                : "ORDER BY max_round_event_time DESC, prs.sequence" ;
        break ;

    case "diffs" :
        $orderby = $isdesc == true
                ? "ORDER BY date_diffable, prs.sequence"
                : "ORDER BY date_diffable DESC, prs.sequence" ;
        break ;

    case "round" :
    case "state" :
        $orderby = $isdesc == true
                ? "ORDER BY prs.sequence DESC"
                : "ORDER BY prs.sequence" ;
        break ;

    default:
        $orderby = "ORDER BY nameofwork";
        break ;
}

$sql = SqlTemplate($username, $orderby);

$rows = $dpdb->SqlRows($sql);
// sweep through the rows, merge round_id's for the same project.
$sums = array();
foreach( $rows as$row) 
{
    if( $chkavail && preg_match("/_avail/", $row['state']))
        continue ;

    if( $chkinprog && ( $row['pages_active'] == 0 ) ) 
        continue ;

    // skip rows the user isn't interested in
    if( $is_rnd_chk[$row['task_code']]) 
        continue;

    if(isset($work))
    {
        if( $work['projectid'] == $row['projectid'] ) 
        {
            $work['round_count'] .= 
                        " {$row['task_code']}({$row['pages_mine']})" ;
        }
        else 
        {
            $sums[] = $work ;
            $work = $row;
            $work['round_count'] = 
                        "{$row['task_code']}({$row['pages_mine']})" ;
        }
    }
    else 
    {
        $work = $row;
        $work['round_count'] = 
                        "{$row['task_code']}({$row['pages_mine']})" ;
    }
}

// handle the last row.
if( isset( $work ) )
    $sums[] = $work ;

$tbl->SetRows( $sums ) ;

//------------------------------------------------------------------
// Draw the page.
//-----------------------------------------------------------------

// display header 
$args = array() ;
$args['js_file'] = "my.js";

theme_header(_("My Projects"), false, $args);
// add end table - theme has started a phantom table.
echo "</table>";


$titlearg="" ;


if(    $User->IsSiteManager() ||  $User->IsProjectFacilitator())
{
    $titlearg = " - " . $username;
    echo "<form action='#' method='get'><p>";
    echo _("See projects that another user has worked on") . ": ";
    echo "<input type='text' name='username' value='$username'>";
    echo "<input type='submit' value='" . attr_safe(_("Refresh")) . "'>";
    echo "</p></form>\n";
}



echo "
 <!-- $sql -->

<div class='center content'>
<h2>".(_("My projects")) . $titlearg . "</h2>

<form id='mypform' name='mypform' method='post' action=''>
  <input type='hidden' name='vsort' value='$vsort' />
  <input type='hidden' name='vdesc' value='$isdesc' />

  "._("Only include projects having: ")."

  "._("My Pages In Progress")."
    <input type='checkbox' name='chkinprog' ".
        ($chkinprog ? "checked='checked'" : "")."
                                    onclick='submitform()' />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  "._("Pages Available")."
    <input type='checkbox' name='chkavail' "
    .($chkavail ? "checked='checked'" : "")."
                                    onclick='submitform()' />
        <br />
  " . _("Include projects worked in:") . "&nbsp;&nbsp;&nbsp;\n";

    foreach(RoundIdsInOrder() as $roundid) 
    {
        echo "&nbsp;&nbsp;&nbsp;
              $roundid<input type='checkbox' name='$roundid' "
            . ($is_rnd_chk[$roundid] ? " CHECKED" : "" )
            . " onclick='submitform()' />\n";
    }
echo "
    </form>\n";

$tbl->EchoTableNumbered() ;

echo "</div>\n";

// add table to balance phantom table closure in theme
echo "<table><tr><td>";
theme_footer();
exit;

// --------------------------------------------------------------------
// column functions 
// -------------------------------------------------------------------

function SqlTemplate($username, $orderby ) {
    return "
        SELECT
            pe.projectid,
            pe.username,
            p.nameofwork AS title,
            p.authorsname AS author,
            p.state,
            pe.task_code,
            MAX(pe.event_time) AS date_diffable,
            MAX(pe.event_time) AS max_round_event_time,

            SUM(CASE WHEN pe.event_type IN ('check_out',
                'save_temp', 'reopen', 'retrieve') THEN 1
                ELSE 0 END) AS pages_active,
            SUM(CASE WHEN pe.event_type = 'save_done'
                THEN 1 ELSE 0 END) AS pages_mine
        FROM
            page_events AS pe

        JOIN
            projects AS p
            ON pe.projectid = p.projectid

        JOIN 
            project_round_sequence AS prs
            ON p.sequence_code = prs.sequence_code
            AND CONCAT(p.state, '.') LIKE CONCAT(prs.roundid, '.%' )

        LEFT JOIN
            page_events AS pe2
            ON pe.projectid = pe2.projectid
            AND pe.page_name = pe2.page_name
            AND pe.event_id < pe2.event_id
           
        WHERE
            pe.username = '{$username}'
            AND pe.event_type IN (
                'check_out', 'save_temp', 'reopen', 
                'retrieve', 'save_done')
            AND pe2.event_id IS NULL
        GROUP BY
            pe.projectid,
            pe.task_code
            {$orderby}";
}

function _round_code($row)
{
    return preg_replace("/\..*$/", "", $row['state']);
}
    
// ----------------------------------------------------------------

function _round_count($row) 
{
    return $row['round_count'] ;

}

// ---------------------------------------------------------------

function _mypagecount($row) 
{
    return $row['mypagecount'] ; 
}

// -------------------------------------------------------------------------

function _nameofwork($row) 
{
    global $code_url;
    return "<a href='$code_url/project.php"
            . "?projectid={$row['projectid']}' >"
            . h( $row['title'] ) . "</a>\n";
}

// -------------------------------------------------------------------------

function _event_time($row)
{
    return _daysAgo( $row['max_round_event_time'] ) ;
}

// -------------------------------------------------------------------------

function _pages_editable($row)
{
    list($taskcode, $avail) 
                    = preg_split("/\..*_/", "", $row['state']);
    return $avail == '_avail' && $taskcode == $row['task_code']
        ? "Yes" : "" ; 
}


// -------------------------------------------------------------------------

function _pages_active($row)
{
    global $code_url;
    return $row['pages_active'] != 0  
        ? "<a href='$code_url/project.php"
                . "?projectid={$row['projectid']}' >"
                . $row['pages_active']
                . "</a>\n"
        : "" ;
}

// -------------------------------------------------------------------------

function _pages_diffable($row)
{
    // global $code_url;
    // $url = url_for_project($row['projectid']);
    // $url = "$code_url/project.php?id={$row['projectid']}" ;
    $prompt = $row['pages_diffable'] > 0 ? _("Yes") : _("No") ;
    return link_to_differ($prompt);
    return "<a href='$code_url"
        . "/tools/proofers/differ.php"
        . "?projectid={$row['projectid']}'>"
        . ( ( $row['pages_diffable'] > 0 ) 
            ? _("Yes")
            : _("No") )
        . "</a>\n";
}

function _date_diffable($row)
{
    // global $code_url;
    $projectid = $row['projectid'];
    $ddate = $row['date_diffable'] ;
    $ago = _daysAgo($ddate);

    if($ddate == "") {
        $text = _("(na)");
    }
    else if($ago == 0) {
        $text = _("today");
    }
    else {
        $text = $ago;
    }
    return link_to_differ($projectid, $text);

/*
    if( ! $ddate ) 
    {
        $text = _("(na)");
    }
    else
    {
        $ago = _daysAgo($ddate);
        $text = ( ! $ago )
            ? _("Today") 
            : $ago ;
    }
    $url = "$code_url/project.php?id={$row['projectid']}" ;

    return "<a href='$code_url"
        . "/tools/proofers/differ.php"
        . "?projectid={$row['projectid']}"
        . "&amp;show_file_size=0"
        . "&amp;select_by_user'>"
        . $text
        . "</a>\n";
*/
}

function _daysAgo($event_time) {
    return round( ( time() - $event_time )
        / 24 / 60 / 60 ) ;
}

/*
function mycss()
{
    return "
    body {
       width: 100%;
       margin: 0;
       padding: 0;
       font-size: normal;
       color: #4F5155;
       background-color: #FFFFFF;
       line-height: 1.4em;
    }

    .content {
        margin: 0 2% 0 2%;
        width: 100%;
        min-height: 2em;
    }

    .dptable {
        font-size: 95%;
        border-width: 1px;
        border-color: #CCC;
        border-collapse: collapse;
        margin-bottom: 2em;
        height: 10%;
        width: 96%;
    }

    td.dptable {
        padding: 1px 3px;
    }

    th {
       background-color: #e0e8dd;
        color: #000000;
        padding: 3px 3px;
        text-align: left;
        border-color: gray;
        border-width: 1px;
    }

    tr.even td {
    }

    tr.odd td {
       background-color: #e0e8dd;
    }\n";
}
*/

    // vim: sw=4 ts=4 expandtab
?>
